<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // 使用
    let promise = new Promise((resolve, reject) => {
      if (true) {
        resolve('成功')
      } else {
        reject('失败')
      }
    })
    promise.then(res => {
      // success
    }, err => {
      // error
    })

    /* 模拟promise */
    class myPromise {
      constructor(fn) {
        this.resolveCallback = []
        this.rejectCallback = []

        this.state = 'pending'
        this.value = ''
        this.reason = ''
        fn(this.resolve.bind(this), this.reject.bind(this))
      }

      resolve (value) {
        if (this.state === 'pending') {
          this.state = 'fulfilled';
          this.value = value;

          this.resolveCallback.forEach(cb => cb(value))
        }
      }
      reject(reason) {
        if (this.state === 'pending') {
          this.state = 'rejected';
          this.reason = reason;

          this.rejectCallback.forEach(cb => cb(reason))
        }
      }

      then(onFulfilled, onRejected) {
        if (this.state === 'pending') {
          this.resolveCallback.push(onFulfilled)
          this.rejectCallback.push(onRejected)
        }
        if (this.state === 'fulfilled') {
          onFulfilled(this.value)
        }

        if (this.state === 'rejected') {
          onRejected(this.reason)
        }
      }
    }


    let p = new myPromise((resolve, reject) => {
      setTimeout(() => {
        reject('失败')
      }, 1000);
    })
    p.then(res => {
      console.log(res, 'res');
    }, err => {
      console.log(err, 'err');
    })
  </script>
</body>
</html>